//begin 公共变量




//end 公共变量

//begin 配置
function trgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
/***扩展editors的datetimebox方法*****/
$.extend($.fn.datagrid.defaults.editors, {
    numberspinner: {
        init: function(container, options){
            var input = $('<input type="text">').appendTo(container);
            return input.numberspinner(options);
        },
        destroy: function(target){
            $(target).numberspinner('destroy');
        },
        getValue: function(target){
            return $(target).numberspinner('getValue');
        },
        setValue: function(target, value){
            $(target).numberspinner('setValue',value);
        },
        resize: function(target, width){
            $(target).numberspinner('resize',width);
        }
    },
    datetimebox: {//datetimebox就是你要自定义editor的名称
        init: function(container, options){
            var editor = $('<input />').appendTo(container);
            editor.enableEdit = false;
            editor.datetimebox(options);
            return editor;
        },
        getValue: function(target){
            var new_str = $(target).datetimebox('getValue').replace(/:/g,'-');
            new_str = new_str.replace(/ /g,'-');
            var arr = new_str.split("-");
            var datum = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5]));
            var timeStamp = datum.getTime();
        
            return new Date(timeStamp).format("yyyy-MM-dd hh:mm:ss");
        //return timeStamp;
        },
        setValue: function(target, value){
            if(value)
                $(target).datetimebox('setValue',new Date(value).format("yyyy-MM-dd hh:mm:ss"));
            else
                $(target).datetimebox('setValue',new Date().format("yyyy-MM-dd hh:mm:ss"));
        },
        resize: function(target, width){
            $(target).datetimebox('resize',width);        
        },
        destroy: function(target){
            $(target).datetimebox('destroy');
        }
    }
});
$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var $clickedDg;
var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){
        return true
    }
    if ($clickedDg.datagrid('validateRow', editIndex)){
        $clickedDg.datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function append(dg){
    $clickedDg =$(dg);
    var row = $clickedDg.datagrid('getSelected');
    if (endEditing()){
        
        $clickedDg.datagrid('appendRow',{
            c1:row.c1,
            c2:row.c2,
            c3:row.c3,
            c4:row.c4,
            c5:row.c5,
            c6:row.c6,
            c7:row.c7
        });
        editIndex = $clickedDg.datagrid('getRows').length-1;
        $clickedDg.datagrid('selectRow', editIndex)
        .datagrid('beginEdit', editIndex);
    }
}
function onClickCell(index, field){
    $clickedDg =$(this);
    if (endEditing()){
        $clickedDg.datagrid('selectRow', index)
        .datagrid('editCell', {
            index:index,
            field:field
        });
        editIndex = index;
		
    }
}

function keydown(e){
    var keyName;
    var e=e||event;
    var currKey=e.keyCode||e.which||e.charCode;
    if(currKey==32) {
        if (!endEditing()){
            /*
			var row = $clickedDg.datagrid('getSelected');
			console.log(row.power);
			var rows = $("#dg").datagrid('getData');
			console.log(rows);
            jsvalue_station[0][3] = 98.99;
			//sampling_chart1.redraw();
			//sampling_chart1.series[0].setData(jsvalue_station[0]);
			sampling_chart1.series[0].update({
				series: [{
							name: dataName,
							data: jsvalue_station[0]
						}]
			});*/
            $clickedDg.datagrid('endEdit',editIndex);
			
        }
    }
/*if((currKey>7&&currKey<14)||(currKey>31&&currKey<47))
　 {
　 　   switch(currKey)
   　 　 {
	　 　 　 case 8: keyName = "[退格]"; break;
	　 　 　 case 9: keyName = "[制表]"; break;
	　 　 　 case 13:keyName = "[回车]"; break;
	　 　 　 case 32:keyName = "[空格]"; break;
	　 　 　 case 33:keyName = "[PageUp]";   break;
	　 　 　 case 34:keyName = "[PageDown]";   break;
	　 　 　 case 35:keyName = "[End]";   break;
	　 　 　 case 36:keyName = "[Home]";   break;
	　 　 　 case 37:keyName = "[方向键左]";   break;
	　 　 　 case 38:keyName = "[方向键上]";   break;
	　 　 　 case 39:keyName = "[方向键右]";   break;
   　 　 　   case 40:keyName = "[方向键下]";   break;
	　 　 　 case 46:keyName = "[删除]";   break;
	　 　 　 default:keyName = "";    break;
　 　   }
　 　   
　 }*/
　 
}

function generate_grid(module,dg,i,dgHeight) {
    
    if(jsparam.data[i].length < 5) {
        dgHeight = (jsparam.data[i].length+1) * 25 +28 +30;
    }
    $(dg).css("height",dgHeight);
    $(dg).datagrid({
        title: jsparam.title[i],
        singleSelect: true,
        fitColumns:true,
        border: false,
        rownumbers: true,
        columns: jsparam.columns[i],
        data: jsparam.data[i],
        onClickCell: onClickCell,
        toolbar:[{
            text:'导入文件',
            handler:function(){
                sendNSCommand('importFile',module,jsparam.title[i],dg);
            }
        }]


    });
}
function generateDg() {
    for(i=0;i<dg.length;i++) {
        //        $(dg[i]).css("width",window_width);
        var dgHeight=310;
        if(jsparam.data[i].length < 5) {
            dgHeight = (jsparam.data[i].length+1) * 25 +28 +30;
        }
        $(dg[i]).css("height",dgHeight);
        $(dg[i]).datagrid({
            title: jsparam.title[i],
            singleSelect: true,
            border: false,
            rownumbers: true,
            columns: jsparam.columns[i],
            data: jsparam.data[i],
            onClickCell: onClickCell,
            toolbar:[{
                text:'导入文件',
                handler:append
            }]

        });

    }
}

//end 配置		
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function showTime(d) {
    var vYear = d.getFullYear();
    var vMon = d.getMonth() + 1;
    var vDay = d.getDate();
    var h = d.getHours();
    var m = d.getMinutes();
    var se = d.getSeconds();
    var s = vYear+"-"+ (vMon < 10 ? "0" + vMon : vMon)+"-" + (vDay < 10 ? "0" + vDay : vDay)+" " + (h < 10 ? "0" + h : h)+":" + (m < 10 ? "0" + m : m)+":" + (se < 10 ? "0" + se : se);
    return s;
}
function showDate(d) {
    var vYear = d.getFullYear();
    var vMon = d.getMonth() + 1;
    var vDay = d.getDate();
    var s = vYear+"-"+ (vMon < 10 ? "0" + vMon : vMon)+"-" + (vDay < 10 ? "0" + vDay : vDay);
    return s;
}
/**
	 * easyui Datagrid百分比显示宽度
	 */
function fixWidth(percent)  {  
    return (doc_width - 240 - 40) * percent ;//根据自身情况更改
}  

function getData(){
    var rows = [];
    for(var i=0; i<jsvalue_station[0].length; i++){
        var dateStr;
        var clonePresentDay = new Date(presentDay);
        clonePresentDay.setMinutes(clonePresentDay.getMinutes() + 15 * (i+1));
        dateStr = clonePresentDay.Format("hh:mm");
        
        rows.push({
            date: dateStr,
            power: jsvalue_station[0][i]
        });
        
    }
    return rows;
}

function getTimeChartOptions(module,cid,ctype,ctitle,csubtitle,cxlabel,cylabel,ccate,cdata) {
    var presentDay = new Date();
    var options = {
        chart: {
            renderTo: cid,
            borderRadius: 5,
            type:ctype
        /*spacingTop: 3,
        spacingRight: 10,
        spacingBottom: 3,
        spacingLeft: 0*/
        },
        title: {
            text: ctitle,
            align: 'left',
            style:{
                fontSize:'14'
			
            }
        },
        subtitle: {
            text: csubtitle
        },
        xAxis: {
            //categories: ccate
            type: 'datetime',
            dateTimeLabelFormats: {
                millisecond: '%H:%M:%S.%L',
                second: '%H:%M:%S',
                minute: '%H:%M',
                hour: '%H:%M',
                day: '%m-%d',
                week: '%m-%d',
                month: '%Y-%m',
                year: '%Y'
            }
        },
        yAxis: {
            //            min: 0,
            title: {
                text: cylabel
            }
        },
        plotOptions: {
            series: {
                //stacking: 'normal'
                //pointIntervalUnit: null,
                //pointInterval: null,
//                pointStart: Date.UTC(presentDay.getFullYear(),presentDay.getMonth(),presentDay.getDate(),presentDay.getHours(),presentDay.getMinutes(),0),
                allowPointSelect: true,
                marker: {
                    radius: 3
                }
            }
        },
        legend: {
            floating: true,
            align: 'right',
            verticalAlign: 'top',
            margin: 0,
            padding: 0,
            borderWidth: 0
		
        },
        credits:{
            enabled: false // 禁用版权信息
        },
        series: cdata
    };

    if(module==0 ||module == 1) {
        options.plotOptions.series.pointStart = Date.UTC(presentDay.getFullYear(),presentDay.getMonth(),presentDay.getDate(),0,15,0);
        options.plotOptions.series.pointStart = Date.UTC(presentDay.getFullYear(),0,1,0,15,0);
        options.plotOptions.series.pointInterval=900000;
    }
    if(module == 2) {
         options.plotOptions.series.pointStart = Date.UTC(presentDay.getFullYear(),presentDay.getMonth(),1,0,0,0);
        options.plotOptions.series.pointIntervalUnit='day';
    }
    if(module == 3) {
         options.plotOptions.series.pointStart = Date.UTC(presentDay.getFullYear(),0,1,0,0,0);
        options.plotOptions.series.pointIntervalUnit='month';
    }
    return options;
} 

function getMixOptions(cid,ctitle,csubtitle,cxlabel,cylabel,ccate,cdata) {
    var options = {
        chart: {
            renderTo: cid,
            borderRadius: 5
        /*spacingTop: 3,
        spacingRight: 10,
        spacingBottom: 3,
        spacingLeft: 0*/
        },
        title: {
            text: ctitle,
            align: 'left',
            style:{
                fontSize:'14'
			
            }
        },
        subtitle: {
            text: csubtitle
        },
        xAxis: {
            //categories: ccate
            type: 'datetime',
            dateTimeLabelFormats: {
                millisecond: '%H:%M:%S.%L',
                second: '%H:%M:%S',
                minute: '%H:%M',
                hour: '%H:%M',
                day: '%m-%d',
                week: '%m-%d',
                month: '%Y-%m',
                year: '%Y'
            }
        },
        yAxis: {
            //            min: 0,
            title: {
                text: cylabel
            }
        },
        plotOptions: {
            series: {
                //stacking: 'normal'
                //pointIntervalUnit: null,
                //pointInterval: null,
                pointStart: Date.UTC(presentDay.getFullYear(),presentDay.getMonth(),presentDay.getDate(),presentDay.getHours(),presentDay.getMinutes(),0),
                allowPointSelect: true,
                marker: {
                    radius: 3
                }
            }
        },
        legend: {
            floating: true,
            align: 'right',
            verticalAlign: 'top',
            margin: 0,
            padding: 0,
            borderWidth: 0
		
        },
        credits:{
            enabled: false // 禁用版权信息
        },
        series: cdata
    };

    if(module==0 ||module == 1) {
        options.plotOptions.series.pointInterval=900000;
    }
    if(module == 2) {
        options.plotOptions.series.pointIntervalUnit='day';
    }
    if(module == 3) {
        options.plotOptions.series.pointIntervalUnit='month';
    }
    return options;
} 

function getPieOptions(cid,ctitle,cdata) {
	
    var options = {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie',
            renderTo: cid,
            borderRadius: 5
        },
        title: {
            text: ctitle,
            align: 'left',
            style:{
                fontSize:'14'
							
            }
        },
        tooltip: {
            pointFormat: item_format
        },
        legend: {
            floating: true,
            align: 'right',
            verticalAlign: 'top',
            margin: 0,
            padding: 0,
            borderWidth: 0
						
        },
        credits:{
            enabled: false // 禁用版权信息
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false/*,
                    format: item_format,
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }*/
                },
                showInLegend: true
            }
        },
        series: [{
            innerSize: '80%',
            colorByPoint: true,
            data: cdata
        }]
    }; 
    return options;
}
    
function getOptions(cid,ctype,ctitle,csubtitle,cxlabel,cylabel,ccate,cdata) {
	
    var options = {
        chart: {
            type: ctype,
            renderTo: cid,
            borderRadius: 5
        },
        title: {
            text: ctitle,
            align: 'left',
            margin: 0,
            style:{
                fontSize:'14',
                fontWeight:'bold'
            }
        },
        subtitle: {
            text: csubtitle
        },
        xAxis: {
            tickInterval: 1,
            categories: ccate,
            title: {
                text: cxlabel
            }
        },
        yAxis: {
            //            min: 0,
            title: {
                text: cylabel
            }
        },
        //        tooltip: {
        //            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
        //            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
        //                '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
        //            footerFormat: '</table>',
        //            shared: true,
        //            useHTML: true
        //        },
        legend: {
            floating: true,
            align: 'right',
            verticalAlign: 'top',
            margin: 0,
            padding: 0,
            borderWidth: 0
				
        },
        lang: {
            
        },
        tooltip: {
            formatter:function(){
                return this.x + '<br><strong>'+this.series.name  + '：' + Highcharts.numberFormat(this.y,2,'.') + '</strong>';
            }
        },
        credits:{
            enabled: false // 禁用版权信息
        },
        plotOptions: {
            series: {
                stacking: ''
            },
            column: {
                dataLabels: {
                    enabled: true,
                    color: '',
                    style: {
                        fontWeight: 'bold'
                    }

                },
                pointPadding: 0.2,
                borderWidth: 0
            },
            bar: {
                cursor: 'pointer',
                point: {
                    events: {
                        click: function() {
                        //            				$.messager.alert("","{point.y:.1f}");
                        }
                    }
                },
                dataLabels: {
                    enabled: false,
                    format: '{point.y:.2f}',
                    style: {
                        fontWeight: 'bold'
                    }

                }
            }
        },
        series: cdata
    };
    return options;
}
function setCellImg(v){
    return '<img src="'+v+'"/>'
}
